<template>
  <!-- 添加用户对话框 -->
  <el-dialog title="修改权限" :visible.sync="dialogVisible" @close="close" width="45%">

    <!-- 主体 -->
    <el-tree ref="tree" :data="RightsTreeList" :default-checked-keys="defKeys" :props="{
          children: 'children',
          label: 'authName'
        }" node-key="id" show-checkbox accordion>
    </el-tree>
    <!-- 底部 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="allotRight">提交</el-button>
    </span>

  </el-dialog>
</template>

<script>
export default {
  name: 'SetRight',
  data() {
    return {
      dialogVisible: this.diashowSetRight, //弹窗开关
      RightsTreeList: null,    //树状权限列表
      defKeys: this.defKeys1   //默认选中的树节点
    }
  },

  props: {
    diashowSetRight: Boolean,  //弹窗开关
    defKeys1: Array,
    roleId: Number
  },

  watch: {
    diashowSetRight() {   //监听弹窗值变化
      this.dialogVisible = this.diashowSetRight
      if (this.dialogVisible) {
        this.getRights()
      }
    },
    defKeys1() {
      this.defKeys = this.defKeys1
    }
  },

  methods: {
    close() {  //监听关闭弹窗
      this.$emit('EmptydefKeys')
      this.$emit('OutdiashowSetRight')

    },
    getRights() {  //获取树状权限列表
      this.RightsTreeList = null  //初始化权限列表
      this.$http.get('rights/tree').then(res => {
        if (res.data.meta.status !== 200) return
        this.RightsTreeList = res.data.data
      })
    },
    allotRight() {  //点击为管理员分配权限
      //展开并整合成数组
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ]
      let rids = keys.join(',')
      this.$http.post(`roles/${this.roleId}/rights`, { rids }).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$mess(res.data.meta.msg, 'error')
        }
        this.$mess(res.data.meta.msg, 'success');
        this.$emit('getRoles')
        this.$emit('OutdiashowSetRight')
      })

    }
  },
}
</script>

<style>
</style>